﻿using SHRIS.MIS.Common.Enum.Base;
using SHRIS.MIS.Common.Util;
using StackExchange.Redis;
using System;
using System.Configuration;

namespace SHRIS.MIS.Common.CacheHelper
{
    public static class RedisHelper
    {
        public static string StringGet(string key)
        {
            IDatabase Cache = Connection.GetDatabase(int.Parse(GlobalContext.SystemConfig.Cache_Redis_Db));
            return Cache.StringGet(GlobalContext.SystemConfig.Cache_Redis_Area + "_" + key);
        }
        public static bool KeyExists(string key)
        {
            IDatabase Cache = Connection.GetDatabase(int.Parse(GlobalContext.SystemConfig.Cache_Redis_Db));
            var nkey = GlobalContext.SystemConfig.Cache_Redis_Area + "_" + key;
            return Cache.KeyExists(nkey) && !string.IsNullOrEmpty(Cache.StringGet(nkey));
        }
        public static bool StringSet(string key, string value, TimeSpan? ts = null)
        {
            IDatabase Cache = Connection.GetDatabase(int.Parse(GlobalContext.SystemConfig.Cache_Redis_Db));
            return Cache.StringSet(GlobalContext.SystemConfig.Cache_Redis_Area + "_" + key, value, ts);
        }
        public static bool KeyDelete(string key)
        {
            IDatabase Cache = Connection.GetDatabase(int.Parse(GlobalContext.SystemConfig.Cache_Redis_Db));
            return Cache.KeyDelete(GlobalContext.SystemConfig.Cache_Redis_Area + "_" + key);
        }

        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(GlobalContext.SystemConfig.Cache_Redis_Configuration);
        });
        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }
    }
}
